package cn.virens.packet;

import java.util.Arrays;

import org.tio.core.intf.Packet;

import cn.virens.common.ByteUtil;

public class ReadPacket extends Packet {
	private static final long serialVersionUID = 1L;
	protected final static String EMPTY_VALUE = "";
	protected final static byte[] EMPTY_BYTES = new byte[0];

	protected int seq = 0;
	protected int len = 0;
	protected String ver = EMPTY_VALUE;
	protected String cmd = EMPTY_VALUE;
	protected byte[] data = EMPTY_BYTES;

	public int seq() {
		return seq;
	}

	public void seq(int seq) {
		this.seq = seq;
	}

	public int len() {
		return len;
	}

	public void len(int len) {
		this.len = len;
	}

	public String ver() {
		return ver;
	}

	public void ver(String version) {
		this.ver = version;
	}

	public String cmd() {
		return cmd;
	}

	public void cmd(String command) {
		this.cmd = command;
	}

	public byte[] data() {
		return data;
	}

	public void data(byte[] data) {
		this.data = data;
	}

	public void data(String hex) {
		this.data = ByteUtil.toByte(hex);
	}

	public byte data(int index) {
		if (data == null) {
			throw new IllegalArgumentException("data is null");
		} else if (index < 0 || index >= data.length) {
			throw new IllegalArgumentException("index is error");
		} else {
			return data[index];
		}
	}

	public byte[] data(int start, int length) {
		if (data == null) {
			throw new IllegalArgumentException("data is null");
		} else if (start < 0 || start >= data.length) {
			throw new IllegalArgumentException("start is error");
		} else if (length > data.length) {
			return Arrays.copyOfRange(data, start, data.length);
		} else {
			return Arrays.copyOfRange(data, start, start + length);
		}
	}

	@Override
	public String toString() {
		return "ReadPacket [seq=" + seq + ", cmd=" + cmd + ", data=" + ByteUtil.toHex(data) + "]";
	}

}
